package com.javacoo.swing.core.monitor;

import com.javacoo.swing.core.constant.Constant;
import com.javacoo.swing.core.event.*;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.CookieStorage;
import com.teamdev.jxbrowser.chromium.LoadURLParams;
import com.teamdev.jxbrowser.chromium.NetworkDelegate;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * 支付宝商家监控基类
 * <p>说明:</p>
 * <li></li>
 *
 * @Author DuanYong
 * @Since 2019/9/1 10:37
 * @Version 1.0
 */
public abstract class BaseAliPayMonitorWindow extends AbstractMonitorWindow {

    /**
     * 系统LOGO图标
     */
    private static final String SYSTEM_LOGIN_LOGO = "icons/logo_yellow.png";
    /**
     * 登录
     */
    private static final String LOGIN_URL = "https://auth.alipay.com/login/homeB.htm";
    /**
     * 登录成功
     */
    private static final String LOGIN_OK_URL = "loginResultDispatch.htm";
    /**
     * 标题
     */
    private static final String TITLE = "登录支付宝";
    /**
     * cookie key
     */
    private static final String COOKIE_NAME = "CLUB_ALIPAY_COM";
    /**
     * 是否已经启动
     */
    private boolean isStart = false;
    @Override
    protected void initWindow() {
        initWebBrowserWindow(LOGIN_URL);
    }
    /**
     * 获取加载URL参数
     * <li></li>
     * @author duanyong@jccfc.com
     * @date 2020/9/15 17:09
     * @return: com.teamdev.jxbrowser.chromium.LoadURLParams
     */
    protected abstract LoadURLParams getLoadURLParams();
    /**
     * 页面加载完成处理
     * <li>适合通过解析页面HTML内容获取数据</li>
     * @author duanyong@jccfc.com
     * @date 2020/9/15 11:04
     * @return: void
     */
    protected abstract void onFinishLoaded();

    protected abstract NetworkDelegate getNetworkDelegate();
    @Override
    protected void doHandleActionEvent(MonitorActionEvent actionEvent) {
        if(ActionType.START == actionEvent.getActionType()){
            this.setMin(actionEvent.getData().get(Constant.TIMER_MIN_KEY));
            this.setMax(actionEvent.getData().get(Constant.TIMER_MAX_KEY));
            startSchedule();
        }else if(ActionType.STOP == actionEvent.getActionType()){
            service.shutdown();
        }else if(ActionType.LOGIN == actionEvent.getActionType()){
            initWebBrowserWindow(LOGIN_URL);
        }
    }

    public void initWebBrowserWindow(String startURL) {
        if(init && !isVisible()){
            setVisible(true);
            MonitorEventBus.getInstance().post(new MonitorActionEvent(ActionType.LOGIN_WIN_VISIBLE));
            return;
        }
        browser = new Browser();
        BrowserView view = new BrowserView(browser);
        browser.getContext().getNetworkService().setNetworkDelegate(getNetworkDelegate());
        browser.loadURL(startURL);
        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if(LOGIN_URL.equals(event.getValidatedURL())) {
                    showLoginWindow(view);
                }
                if(event.getValidatedURL().contains(LOGIN_OK_URL)){
                    browser.loadURL(getLoadURLParams());
                }
                if(event.getValidatedURL().contains(getLoadURLParams().getURL())){
                    setVisible(false);
                    if(!isStart){
                        MonitorEventBus.getInstance().post(new MonitorActionEvent(ActionType.DETAIL_URL_LOADED));
                        isStart = true;
                        parserCookieStorage(browser.getCookieStorage());
                    }else{
                        if(event.isMainFrame()){
                            onFinishLoaded();
                        }
                    }
                }
            }
        });
    }
    /**
     * 显示登陆页面
     * <li></li>
     * @author duanyong@jccfc.com
     * @date 2020/9/14 19:27
     * @param view:
     * @return: void
     */
    private void showLoginWindow(BrowserView view) {
        setTitle(TITLE);
        add(view, BorderLayout.CENTER);
        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        setIconImage(new ImageIcon(SYSTEM_LOGIN_LOGO).getImage());
        // 取得屏幕大小
        Toolkit kit = Toolkit.getDefaultToolkit();
        Dimension oursize = getSize();
        Dimension screensize = kit.getScreenSize();
        // 窗口居中显示
        int x = (screensize.width - oursize.width) / 2;
        int y = (screensize.height - oursize.height) / 2;
        x = Math.max(0, x);
        y = Math.max(0, y);
        setLocation(x, y);
        setResizable(false);
        MonitorEventBus.getInstance().post(new MonitorActionEvent(ActionType.LOGIN_WIN_VISIBLE));
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                //super.windowClosing(e);
                setVisible(false);
                MonitorEventBus.getInstance().post(new MonitorActionEvent(ActionType.LOGIN_WIN_HIDDEN));
            }
            @Override
            public void windowDeactivated(WindowEvent windowEvent) {
                requestFocus();
            }
            @Override
            public void windowIconified(WindowEvent we) {
                setState(JFrame.NORMAL);
            }
        });
        setVisible(true);
        init = true;
    }

    /**
     * 解析CookieStorage获取商户ID
     * <p>说明:</p>
     * <li></li>
     * @Author DuanYong
     * @Since 2019/8/30 22:08
     * @Version 1.0
     * @Params cookieStorage
     */
    private void parserCookieStorage(CookieStorage cookieStorage) {
        cookieStorage.getAllCookies().stream().filter(cookie->COOKIE_NAME.equals(cookie.getName())).forEach(cookie->MonitorEventBus.getInstance().post(new DataEvent(DataType.UID_DATA,cookie.getValue())));
    }
}
